package com.classTest;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.security.auth.login.AccountException;

class Account{
    private String name;
    private int assets;
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public Account(String name,int assets){
        this.name = name;
        this.assets = assets;
    }
    public void save(int assets){
        this.rwLock.writeLock().lock();
        try{
            this.assets += assets;
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"存钱成功，余额为："+this.assets);
        }catch (Exception e){
        }finally {
            this.rwLock.writeLock().unlock();
        }
    }
    public String toString(){
        this.rwLock.readLock().lock();
        try{
            TimeUnit.MILLISECONDS.sleep(10);
            return "账户："+this.name+" 资产："+this.assets;
        }catch (Exception e){
            return null;
        }finally {
            this.rwLock.readLock().unlock();
        }
    }
}

public class test05 {
    public static void main(String[] args)throws Exception{
        Account account = new Account("zhangsan",5);
        int money[] = new int[]{100,200,300};
        for (int i = 0;i < 10;i ++){
            if (i%2 == 0){
                new Thread(()->{
                    for (int j = 0;j < money.length;j ++){
                        account.save(money[j]);
                    }
                },"存款者 - "+ i).start();
            }
            else{
                new Thread(()->{
                    while (true){
                        System.out.println(account);
                    }
                },"取款者 - "+ i).start();
            }
        }
    }
}
